import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'crypto'
import { Encryptor } from '../../../jsondb/jsondb.ts'

interface AESOptions {
  key: string              // 加密密钥
  algorithm?: string       // 加密算法 (默认 aes-256-gcm)
}

export class AESEncryptor implements Encryptor {
  private key: Buffer
  private algorithm: string

  constructor(options: AESOptions) {
    this.key = createHash('sha256')
      .update(options.key)
      .digest()
    this.algorithm = options.algorithm || 'aes-256-gcm'
  }

  encrypt(data: string): string {
    const iv = randomBytes(16)
    const cipher = createCipheriv(this.algorithm, this.key, iv)

    let encrypted = cipher.update(data, 'utf8', 'hex')
    encrypted += cipher.final('hex')

    // 在加密数据前面添加 IV
    return iv.toString('hex') + ':' + encrypted
  }

  decrypt(data: string): string {
    const [ivHex, encryptedData] = data.split(':')
    const iv = Buffer.from(ivHex, 'hex')

    const decipher = createDecipheriv(this.algorithm, this.key, iv)

    let decrypted = decipher.update(encryptedData, 'hex', 'utf8')
    decrypted += decipher.final('utf8')

    return decrypted
  }
}
